import React, {Fragment, PureComponent} from 'react';
import {connect} from 'dva';
import moment from 'moment';
import {Badge, Button, Card, Col, Divider, Form, message, Modal, Row, Select,} from 'antd';
// import StandardTable from '@/components/StandardTable';
import TableList from '@/components/TableList';
import DescriptionList from '@/components/DescriptionList';
import styles from './Flow.less';
import ApplyDetailForm from './sub/ApplyDetailForm';
const {Description} = DescriptionList;

const FormItem = Form.Item;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

const DetailForm = Form.create()(props => {
  const {modalVisible, handleModalVisible, data,} = props;

  return (
    <Modal
      destroyOnClose
      title="外发详情"
      visible={modalVisible}
      onCancel={() => handleModalVisible()}
      maskClosable={false}
    >
      <DescriptionList size="large" title="申请信息" style={{marginBottom: 32}}>
        <Description term="文件名称">{data.fileName || ""}</Description>
        <Description term="申请类型">{data.applyType || ""}</Description>
        <Description term="申请人">{data.applyUserName || ""}</Description>
        <Description term="审核人">{data.auditUserName || ""}</Description>
        <Description term="标题">{data.applyTitle || ""}</Description>
        <Description term="理由">{data.applyReason || ""}</Description>
        <Description term="状态">{data.applyState || "--"}</Description>
        <Description term="接收人">{data.flowVo || "--"}</Description>
      </DescriptionList>
      <Divider style={{marginBottom: 32}}/>
      <DescriptionList size="large" title="审批信息" style={{marginBottom: 32}}>
        <Description term="审核信息">{data.auditRemark || "--"}</Description>
      </DescriptionList>
    </Modal>
  );
});


/* eslint react/no-multi-comp:0 */
@connect(({workspaceModel, loading}) => ({
  workspaceModel,
  loading: loading.models.workspaceModel,
}))
@Form.create()
class Out extends PureComponent {
  state = {
    modalVisible: false,//详情modal
    selectedRows: [],
    formValues: {},
    detail: {},
    waterOptions:[],
    authOptions: [],
  };

  columns = [
    {
      title: '文件名称',
      dataIndex: 'fileDirNames',
      render: fileId => <a onClick={() => this.previewItem(fileId)}>{fileId}</a>,
    },
    {
      title: '审核人',
      dataIndex: 'auditUserCode',
    },
    {
      title: '申请时间',
      dataIndex: 'createTime',
      render: val => <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span>,
    },
    {
      title: '状态',
      dataIndex: 'applyState',
      render(val) {
        // const statusMap = ['default', 'processing', 'success', 'error'];
        // const status = ['关闭', '运行中', '已上线', '异常'];
        // 0申请中1通过2拒绝
        let text = "--";
        let status = "";
        if (val == 0) {
          status = "processing";
          text = "申请中";
        } else if (val == 1) {
          status = "success";
          text = "通过";
        } else if (val == 2) {
          status = "error";
          text = "拒绝";
        }
        return <Badge status={status} text={text}/>;
      },
    },
    {
      title: '操作',
      render: (text, record) => (
        <Fragment>
          {/*<Popconfirm title="是否要删除此行？" onConfirm={() => this.remove(record.id)}>*/}
          {/*<a>删除</a>*/}
          {/*</Popconfirm>*/}
          <Divider type="vertical"/>
          <a onClick={() => this.handleModalVisible(true, record)}>详情</a>
        </Fragment>
      ),
    },
  ];

  componentDidMount() {
    const {dispatch} = this.props;
    dispatch({
      type: 'workspaceModel/queryApplyPageList',
      payload: {applyType: 2, auditType: 0,},
    });

    this.queryOutWaterOptions();
    this.queryOutRightControl();
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const {dispatch} = this.props;
    const {formValues} = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = {...obj};
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      currentPage: pagination.current,
      pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'workspaceModel/queryApplyPageList',
      payload: params,
    });
  };

  previewItem = id => {
    Modal.success(`预览文件 id:${id}`);
  };


  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleSearch = e => {
    e.preventDefault();

    const {dispatch, form} = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
        applyType: 0,
        auditType: 0,
      };

      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'workspaceModel/queryApplyPageList',
        payload: values,
      });
    });
  };


  renderSimpleForm() {
    const {
      form: {getFieldDecorator},
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{md: 8, lg: 24, xl: 48}}>
          {/*<Col md={8} sm={24}>*/}
          {/*<FormItem label="文件名称">*/}
          {/*{getFieldDecorator('fileName')(<Input placeholder="请输入"/>)}*/}
          {/*</FormItem>*/}
          {/*</Col>*/}
          <Col md={8} sm={24}>
            <FormItem label="申请状态">
              {/*0申请中1通过2拒绝*/}
              {getFieldDecorator('applyState')(
                <Select placeholder="请选择" style={{width: '100%'}}>
                  <Option value="">--请选择--</Option>
                  <Option value="0">申请中</Option>
                  <Option value="1">通过</Option>
                  <Option value="2">拒绝</Option>
                </Select>
              )}
            </FormItem>
          </Col>

          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    return this.renderSimpleForm();
  }


  handleModalVisible = (flag, record) => {
    this.setState({
      modalVisible: !!flag,
      selectedItem: record || {},
    });

    if (record) {
      this.queryApplyDetail(record.id);
    }
  };

  //查询申请详情
  queryApplyDetail = id => {
    const {dispatch} = this.props;
    let queryForm = {id: id};
    dispatch({
      type: 'workspaceModel/queryApplyDetail',
      payload: queryForm,
    });
  };
  queryOutWaterOptions = () => {
    const {dispatch} = this.props;
    let params = {dataDictTypeCode: 'out_water_control', status: 0};
    dispatch({
      type: 'workspaceModel/queryDataDict',
      payload: params,
      callback: (res) => {
        if (res.result == "ok" && res.data) {
          let waterOptions = [];
          res.data.dataList.forEach(item => {
            waterOptions.push({label: item.dataDictName, value: item.dataDictValue});
          })
          this.setWaterOptions(waterOptions);

        }
      },
    });
  };
  setWaterOptions = (options) => {
    this.setState({waterOptions: options});
  }
  /**
   * 查询外发的权限
   */
  queryOutRightControl = () => {
    const {dispatch} = this.props;
    let params = {dataDictTypeCode: 'out_right_control', status: 0};
    dispatch({
      type: 'workspaceModel/queryDataDict',
      payload: params,
      callback: (res) => {
        if (res.result == "ok" && res.data) {
          let authOptions = [];
          res.data.dataList.forEach(item => {
            authOptions.push({label: item.dataDictName, value: item.dataDictValue});
          })

          this.setAuthOptions(authOptions);
        }
      },
    });
  };
  setAuthOptions = (options) => {
    this.setState({authOptions: options});
  }



  render() {
    const {
      workspaceModel: {data, detail},
      loading,
    } = this.props;
    const {selectedRows, modalVisible,waterOptions,authOptions,} = this.state;
    //上传文件
    const parentMethods = {
      handleModalVisible: this.handleModalVisible,
    };


    return (
      <Card bordered={false}>
        <div className={styles.tableList}>
          <div className={styles.tableListForm}>{this.renderForm()}</div>

          <TableList
            className={styles.tdPadding}
            hideRowSelection={true}
            selectedRows={selectedRows}
            loading={loading}
            data={data}
            columns={this.columns}
            onSelectRow={this.handleSelectRows}
            onChange={this.handleStandardTableChange}
            rowKey={record => record.id}
          />
        </div>

        <ApplyDetailForm waterOptions={waterOptions} authOptions={authOptions} {...parentMethods} record={detail} modalVisible={modalVisible}/>
      </Card>
    );
  }
}

export default Out;
